package com.rainbow.security

import com.rainbow.security.service.MenuService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.access.SecurityConfig
import org.springframework.security.web.FilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource
import org.springframework.stereotype.Component
import org.springframework.util.AntPathMatcher

@Component
class CustomMetadataSource : FilterInvocationSecurityMetadataSource {

    @Autowired
    internal var menuService: MenuService? = null
    internal var antPathMatcher = AntPathMatcher()


    override fun getAllConfigAttributes(): MutableCollection<ConfigAttribute>? {
        return null
    }

    override fun supports(p0: Class<*>?): Boolean {
        return FilterInvocation::class.java.isAssignableFrom(p0)
    }

    override fun getAttributes(o: Any): MutableCollection<ConfigAttribute> {
        val requestUrl = (o as FilterInvocation).getRequestUrl()
        val allMenu = menuService!!.getAllMenu()
        for (menu in allMenu!!) {
            if (antPathMatcher.match(menu.url!!, requestUrl) && menu.roles().size() > 0) {
                val roles = menu.roles()
                val size = roles.size()
                val values = arrayOfNulls<String>(size)
                for (i in 0 until size) {
                    values[i] = roles.get(i).getName()
                }
                return SecurityConfig.createList(values)
            }
        }
        //没有匹配上的资源，都是登录访问
        return SecurityConfig.createList("ROLE_LOGIN")
    }
}